import { CacheOption, BdjfRequest, RequestOption } from "./type";

export class RequestImpl implements BdjfRequest{
    requestOption: RequestOption;
    cacheOption?: CacheOption | undefined;

    constructor(requestOption:RequestOption,cacheOption?:CacheOption){
        this.requestOption = requestOption;
        this.cacheOption = cacheOption;
    }
    closeLoading = ():BdjfRequest=>{
        this.requestOption.hideLoading = true;
        return this;
    }

    openLoading = ()=>{
        this.requestOption.hideLoading = false;
        return this;
    }
    
    setOption = (newOption: RequestOption):BdjfRequest => {
        Object.keys(newOption).forEach(key=>{
            this.requestOption[key] = newOption[key];
        })
        return this;
    }
    setCacheOption = (newOption: CacheOption):BdjfRequest => {
        if(this.cacheOption){
            Object.keys(newOption).forEach(key=>{
                this.cacheOption![key] = newOption[key];
            })
        }else{
            this.cacheOption = newOption;
        }
        return this;
    }

    

    public conflictCacheUrl(): string[]{
        // 将数组中的 RequestBean 的url属性抽取出来作为一个数组返回
        return this.cacheOption?.conflictCacheUrl?.map(request=>{
            return request.requestOption.url;
        })||[]
    }
}

export function createRequest (requestOption:RequestOption,cacheOption?:CacheOption){
    return new RequestImpl(requestOption,cacheOption);
}